package com.taotao.item.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.taotao.item.pojo.Item;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.service.ItemService;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ItemChangeFreeMarkerListener implements MessageListener {

	@Autowired
	private FreeMarkerConfigurer config;
	
	@Autowired
	private ItemService itemService;
	
	@Override
	public void onMessage(Message message) {
		
		if(message instanceof TextMessage) {
			TextMessage textMessage = (TextMessage)message;
			try {
			   String text = textMessage.getText();
			   if(StringUtils.isNotEmpty(text)) {
				   Long itemId = Long.parseLong(text);

				   TbItem tbItem = itemService.getItemById(itemId);
				   
				   TbItemDesc itemDesc = itemService.getDescById(itemId);
				   
				   Item item = new Item(tbItem);
				   
				   generateHtml(item,itemDesc);
				   
			   }
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}

	public void generateHtml(Item item, TbItemDesc itemDesc) throws Exception {
		Configuration configuration = config.getConfiguration();
		
		Template template = configuration.getTemplate("item.ftl");
		
		Map map = new HashMap();
		map.put("item", item);
		map.put("itemDesc", itemDesc);
		
		Writer writer = new FileWriter(new File("F:\\FreeMarker\\item\\"+item.getId()+".html"));
		
		template.process(map, writer);
		
		writer.close();

	}

}
